<template>
  <div class="MyCar">
    <div class="MyCarHeader">
      <span>我的购物车</span>
    </div>
    <div class="MyCarContent">
      <el-table
        @row-click="handleRow"
        :data="tableObj.temporary"
        stripe
        ref="checkTable"
        style="width: 100%; margin-left: 20px"
        @selection-change="handleSelectionChange"
        :row-key="getRowKey"
      >
        <!-- ="() => tableObj.temporary"        -->
        <!-- 购买复选框 -->
        <el-table-column
          type="selection"
          prop=""
          :reserve-selection="true"
          label="购买"
          width="100"
        >
        </el-table-column>

        <el-table-column prop="name" label="产品名称" width="120">
        </el-table-column>

        <el-table-column prop="imgPath" label="图片" width="150">
          <template slot-scope="scope">
            <img
              :src="require('/src/assets/img/' + scope.row.imgPath)"
              width="45"
              height="45"
            />
          </template>
        </el-table-column>

        <el-table-column prop="brand" label="品牌" width="120">
        </el-table-column>

        <el-table-column prop="price" label="价格（1斤）" width="120">
        </el-table-column>

        <el-table-column prop="username" label="商家" width="120">
        </el-table-column>

        <el-table-column prop="" label="" width="35">
          <i class="el-icon-remove-outline" @click="subNumber"></i>
        </el-table-column>

        <el-table-column prop="number" label="数量" width="50">
          <!-- <i class="el-icon-remove-outline"></i> -->
        </el-table-column>

        <el-table-column prop="" label="" width="35">
          <i class="el-icon-circle-plus-outline" @click="plusNumber"></i>
        </el-table-column>

        <el-table-column prop="" label="相关操作" width="150">
          <el-button type="warning" @click="delRow" icon="el-icon-delete"
            >移除</el-button
          >
        </el-table-column>
      </el-table>
      <div class="Pay">
        <span v-show="tableObj.tableData.length !== 0"
          >总额:{{ totalMoney }}</span
        >
        <el-button
          @click="settlementBtn"
          :disabled="totalMoney === 0"
          v-show="tableObj.tableData.length !== 0"
          type="success"
          id="PayButton"
          round
          >结算</el-button
        >
      </div>

      <!-- 支付弹出层 -->
      <el-dialog
        title="请输入支付密码"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-input
          placeholder="支付密码"
          v-model="payPassword"
          clearable
          type="password"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="Payment">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加收货地址弹出层 -->
      <el-dialog
        title="收货地址"
        :visible.sync="dialogAddress"
        width="50%"
        :before-close="handleClose"
      >
        姓名:
        <el-input
          style="margin-top: 10px; width: 90%"
          placeholder="姓名"
          v-model="existName"
          clearable
          type="text"
          :disabled="isNotModify"
        >
        </el-input>
        <br />
        手机号:
        <el-input
          placeholder="手机号"
          v-model="existPhone"
          clearable
          type="text"
          style="margin-top: 10px; width: 90%"
          :disabled="isNotModify"
        >
        </el-input>
        <br />
        收货地址:
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="existAddress"
          maxlength="30"
          show-word-limit
          style="margin-top: 10px; width: 85%"
          :disabled="isNotModify"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogAddress = false">取 消</el-button>
          <el-button @click="addAddress">修改收货信息</el-button>
          <el-button type="primary" @click="saveAddress">确 定</el-button>
        </span>
      </el-dialog>

      <div v-show="tableObj.tableData.length !== 0" class="pages">
        <span>页次:</span
        ><span>{{ tableObj.currentPage }}/{{ tableObj.totalPages }}</span
        ><span>页</span><span>每页显示：</span>
        <span>
          <select name="" id="" v-model="tableObj.number" @change="alterNumber">
            <option
              v-for="(item, index) in tableObj.tableData.length > 6
                ? tableObj.tableData.slice(0, 6)
                : tableObj.tableData"
              :key="index"
              :value="index + 1"
            >
              {{ index + 1 }}
            </option>
          </select>
        </span>
        <span>条</span>
        <span>总记录数：</span>
        <span>{{ tableObj.tableData.length }}条</span>

        <span>
          <el-button @click="getFirst"><span>首页</span></el-button>
          <span>
            <el-pagination
              layout="prev, pager, next"
              :page-size="tableObj.number"
              :current-page="tableObj.currentPage"
              @current-change="handleCurrentChange"
              :total="tableObj.tableData.length"
              style="display: inline-block"
            >
            </el-pagination>
          </span>
          <el-button @click="getLast"><span>末页</span></el-button>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {
  renderFunc,
  changeNumber,
  currentChange,
  getFirstPage,
  getLastPage,
  // oneTeaStore,
} from "../../util/tools";
import { getReq } from "../../util/request";
import { statistic } from "../../util/statistic.js";

export default {
  name: "MyCar",
  data() {
    return {
      tableObj: {
        tableData: [],
        number: 3,
        totalPages: 0,
        currentPage: 1,
        temporary: [],
        // rowData:'',
      },
      isNull: true,
      userId: "",
      teaData: [],
      isCheckedProducts: [],
      index: {},
      totalMoney: 0,
      dialogVisible: false,
      dialogAddress: false,
      payPassword: "",
      existAddress: "",
      existPhone: "",
      existName: "",
      isNotModify: true,
    };
  },
  methods: {
    //分页保持选中结果
    getRowKey(row) {
      // console.log("row:", row);
      return row.teaId;
    },

    alterNumber() {
      changeNumber(this.tableObj);
    },

    handleCurrentChange(val) {
      currentChange(val, this.tableObj);
    },

    getFirst() {
      getFirstPage(this.tableObj);
    },

    getLast() {
      getLastPage(this.tableObj);
    },
    //获取localStorage中的茶叶数据
    getTeaData(value) {
      if (value.id == this.userId) {
        this.$message({
          showClose: true,
          message: "您不能购买自己的商品哟！",
          type: "error",
        });
      } else {
        // console.log('this.rowData:',this.rowData)
        var tea =
          this.$storage.get(this.userId) === null
            ? []
            : this.$storage.get(this.userId);
        var num = tea.reduce((pre, product) => {
          return (pre =
            product.username === value.username && product.name === value.name
              ? pre + 1
              : pre);
        }, 1);
        // console.log("num:",num)

        if (num < 11) {
          this.teaData.unshift(value);

          if (this.$storage.get(this.userId) !== null) {
            this.$storage.remove(this.userId);
            this.$storage.set(this.userId, this.teaData);
          } else {
            this.$storage.set(this.userId, this.teaData);
          }

          this.teaData =
            this.$storage.get(this.userId) === null
              ? []
              : this.$storage.get(this.userId);
          //统计相同的产品数量
          var teaData1 = statistic(this.teaData);

          //渲染界面
          this.tableObj = renderFunc(teaData1, this.tableObj);
          this.$message({
            showClose: true,
            message: "已添加至购物车",
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: "数量达到最多了",
            type: "warning",
          });
        }
      }
    },

    //减数按钮
    subNumber() {
      this.timer = setTimeout(() => {
        this.$nextTick(() => {
          this.totalMoney = this.isCheckedProducts.reduce((pre, product) => {
            console.log(product.number, parseInt(product.price));
            return (pre += product.number * parseInt(product.price));
          }, 0);
        });

        if (this.rowData !== "") {
          // this.rowData.number -=1
          if (this.rowData.number > 1) {
            //可以减的话，对数组进行加工
            this.tableObj.tableData = this.tableObj.tableData.map((item) => {
              //找到该行对应的数据
              if (
                this.rowData.name === item.name &&
                this.rowData.username === item.username
              ) {
                //从localStorage中获取购物车中的数据
                var tea1 =
                  this.$storage.get(this.userId) === null
                    ? []
                    : this.$storage.get(this.userId);
                //遍历找到最后一个数据，这个数据与点击的同一行数据相同
                for (let i = tea1.length - 1; i >= 0; i--) {
                  if (
                    tea1[i].username === this.rowData.username &&
                    tea1[i].name === this.rowData.name
                  ) {
                    //对购物车中的商品信息进行修改
                    tea1.splice(i, 1);
                    this.$storage.remove(this.userId);
                    this.$storage.set(this.userId, tea1);
                    break;
                  }
                }
                item.number -= 1;
                return item;
              }
              return item;
            });
          } else {
            alert("数量已经最低了");
            return;
          }
        } else {
          return;
        }
      }, 0);
    },

    //加数按钮
    plusNumber() {
      this.timer = setTimeout(() => {
        // console.log('this.isCheckedProducts::',this.isCheckedProducts)
        this.$nextTick(() => {
          this.totalMoney = this.isCheckedProducts.reduce((pre, product) => {
            console.log(product.number, parseInt(product.price));
            return (pre += product.number * parseInt(product.price));
          }, 0);
        });

        if (this.rowData !== "") {
          if (this.rowData.number < 10) {
            this.rowData.number += 2;
            this.tableObj.tableData = this.tableObj.tableData.map((item) => {
              //找到该行对应的数据
              if (
                this.rowData.name === item.name &&
                this.rowData.username === item.username
              ) {
                //从localStorage中获取购物车中的数据
                var tea1 =
                  this.$storage.get(this.userId) === null
                    ? []
                    : this.$storage.get(this.userId);
                //遍历找到最后一个数据，这个数据与点击的同一行数据相同
                for (let i = 0; i <= tea1.length - 1; i++) {
                  // console.log("tea1")
                  if (
                    tea1[i].username === this.rowData.username &&
                    tea1[i].name === this.rowData.name
                  ) {
                    //对购物车中的商品信息进行修改
                    var addTea = tea1.slice(i, i + 1)[0];
                    tea1.splice(i, 0, addTea);
                    // tea1.splice(i,1)
                    // this.$storage.remove(this.userId)
                    this.$storage.set(this.userId, tea1);
                    // break
                    // console.log(addTea)
                    break;
                  }
                }
                item.number -= 1;
                return item;
              }
              return item;
            });
          } else {
            alert("已经达到限购了！！");
            // console.log()
          }
        } else {
          return;
        }
      }, 0);
    },

    //移除某一行的数据
    delRow() {
      this.timer = setTimeout(() => {
        // console.log("....",this.rowData)
        if (this.rowData != "") {
          if (window.confirm("确定删除吗？")) {
            const { username, name } = this.rowData;
            //获取localStorage中的数据
            var tea =
              this.$storage.get(this.userId) === null
                ? []
                : this.$storage.get(this.userId);
            // console.log("删除前:",tea)
            //去掉要删除的数据
            // console.log('teaData1')
            tea = tea.filter((item) => {
              return !(item.username === username && item.name === name);
            });

            //统计相同茶叶的数量
            var teaData1 = statistic(tea);

            //渲染界面
            this.tableObj = renderFunc(teaData1, this.tableObj);

            //重新添加到localStorage中
            this.$storage.remove(this.userId);
            this.$storage.set(this.userId, tea);
          }
        } else {
          return;
        }
      }, 0);
    },

    //获取该行数据
    handleRow(row) {
      this.rowData = row;
      // console.log("this.rowData",this.rowData.number)
    },

    //处理多选框问题
    handleSelectionChange(row) {
      // var teaData1 = statistic(this.teaData)
      // renderFunc(teaData1,this.tableObj)
      this.$nextTick(() => {
        //有勾选，就添加到row数组中
        this.isCheckedProducts = row;
        // console.log("this.isCheckedProducts", this.isCheckedProducts);
        // row =[]
        this.totalMoney = this.isCheckedProducts.reduce((pre, product) => {
          // console.log(product.number,parseInt(product.price))
          return (pre += product.number * parseInt(product.price));
        }, 0);
        if (row.length === 0) {
          this.totalMoney = 0;
        }
      });
    },

    //保存该行选中的
    handleReserve(row) {
      return row.id;
    },

    //点击结算按钮
    settlementBtn() {
      this.dialogAddress = true;
      let getAddress = getReq("user/getAddress", `?id=${this.userId}`);
      getAddress.then(
        (res) => {
          // console.log(res.data);
          this.existAddress = res.data[0].address;
          this.existPhone = res.data[0].phone;
          this.existName = res.data[0].username;

          // this.dialogAddress = false;
        },
        (reason) => {
          throw reason;
        }
      );
    },

    //添加新地址
    addAddress() {
      this.isNotModify = false;
    },

    //保存地址
    saveAddress() {
      this.dialogAddress = false;
      this.dialogVisible = true;
    },

    //关闭弹出层
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },

    //结算按钮，生成订单
    Payment() {
      if (this.payPassword.trim() === "") {
        this.$message.error("密码输入不能为空!");
        this.payPassword = "";
      } else {
        //查询用户密码
        var p0 = new Promise((resolve, reject) => {
          axios
            .get(
              `http://localhost:3000/user/getUserPaypwd?userId=${this.userId}&paypwd=${this.payPassword}`
            )
            .then(
              (response) => resolve(response),
              (error) => reject(error)
            );
        });

        p0.then(
          (response) => {
            this.dialogVisible = false;
            if (response.data.pwdIsRight) {
              // 查询用户余额
              var p1 = new Promise((resolve, reject) => {
                axios
                  .get(
                    `http://localhost:3000/user/getUserMoney?userId=${this.userId}&money=${this.totalMoney}`
                  )
                  .then(
                    (response) => {
                      resolve(response);
                    },
                    (error) => {
                      reject(error);
                    }
                  );
              });
              p1.then(
                (response) => {
                  if (!response.data.isEnough) {
                    alert("您的余额不足！！");
                    return;
                  } else {
                    var p2 = new Promise((resolve, reject) => {
                      //购买成功，减去数据库中的金额
                      axios
                        .post("http://localhost:3000/user/setMoney", {
                          money: this.totalMoney,
                          userId: this.userId,
                        })
                        .then((response) => {
                          resolve(response),
                            (error) => {
                              reject(error);
                            };
                        });
                    });
                    p2.then(
                      (response) => {
                        //修改金额成功的回调
                        if (response.data.isModify) {
                          //修改成功生成订单
                          axios
                            .post("http://localhost:3000/order/insertOrder", {
                              products: this.isCheckedProducts,
                              userId: this.userId,
                              address: this.existAddress,
                              receiver: this.existName,
                              phone: this.existPhone,
                            })
                            .then(
                              (response) => {
                                this.payPassword = "";
                                if (response.data.isInsert) {
                                  //移除购物车中已经购买过的商品
                                  var teaIds = [];
                                  this.isCheckedProducts.forEach((product) => {
                                    teaIds.push(product.teaId);
                                  });
                                  var removedProducts = this.$storage
                                    .get(this.userId)
                                    .filter((item) => {
                                      if (
                                        !teaIds.some((teaId) => {
                                          return teaId === item.teaId;
                                        })
                                      ) {
                                        return item;
                                      }
                                    });
                                  //统计相同茶叶的数量
                                  var teaData1 = statistic(removedProducts);
                                  this.isCheckedProducts = [];
                                  //渲染界面
                                  this.tableObj = renderFunc(
                                    teaData1,
                                    this.tableObj
                                  );
                                  this.$refs.checkTable.clearSelection();
                                  this.totalMoney = 0;
                                  this.$storage.remove(this.userId);
                                  this.$storage.set(
                                    this.userId,
                                    removedProducts
                                  );
                                }
                              },
                              (error) => {
                                console.log(error);
                              }
                            );
                        } else {
                          this.$message({
                            type: "error",
                            message: "金额修改失败!!",
                            duration: 3000,
                          });
                        }
                      },
                      (error) => {
                        console.log(error);
                      }
                    );
                  }
                },
                (error) => {
                  console.log(error);
                }
              );
            } else {
              alert(response.data.msg);
              this.payPassword = "";
            }
          },
          (error) => {
            console.log(error);
          }
        );
      }
    },
  },
  mounted() {
    this.totalMoney = 0;
    // console.log(this.totalMoney)
    // var { tableData,number} = this.tableObj
    this.userId = this.$cookie.get("userId");
    // this.$storage.get(this.userId)
    //获取添加购物车数据
    this.$bus.$on("teaData", this.getTeaData);

    this.teaData =
      this.$storage.get(this.userId) === null
        ? []
        : this.$storage.get(this.userId);
    //统计相同的产品数量
    var newProduct = statistic(this.teaData);

    this.tableObj.number = newProduct.length > 6 ? 6 : newProduct.length;
    //表单渲染数据
    this.tableObj.tableData = this.teaData.length === 0 ? [] : newProduct;
    this.tableObj.totalPages =
      this.tableObj.tableData.length % this.tableObj.number === 0
        ? parseInt(this.tableObj.tableData.length / this.tableObj.number)
        : parseInt(this.tableObj.tableData.length / this.tableObj.number + 1);
    this.tableObj.temporary = this.tableObj.tableData.slice(
      (this.tableObj.currentPage - 1) * this.tableObj.number,
      (this.tableObj.currentPage - 1) * this.tableObj.number +
        this.tableObj.number
    );
    // console.log("this.tableObj", this.tableObj);

    this.tableObj.tableData.forEach(() => {});
  },

  beforeMount() {
    // console.log('组件挂载之前')
  },
  beforeDestroy() {
    // console.log('组件被销毁')
    clearTimeout(this.timer);
  },
};
</script>

<style scoped lang='less'>
.MyCar {
  width: 100%;
  min-height: 800px;
  background-color: white;
  .MyCarHeader {
    width: 100%;
    height: 60px;
    line-height: 60px;
    border-bottom: 1px solid rgb(224, 223, 223);
    margin-bottom: 10px;
    span {
      float: left;
      font-size: 20px;
      margin-left: 20px;
    }
  }
  .MyCarContent {
    width: 100%;
    min-height: 500px;
    .pages {
      margin-top: 30px;
      span {
        margin: 0 15px;
      }
    }
    .Pay {
      width: 100%;
      height: 80px;
      line-height: 80px;
      #PayButton {
        width: 100px;
        float: right;
        margin-right: 20px;
        margin-top: 20px;
      }
      & > span {
        float: right;
        margin-right: 250px;
        // margin-top: 20px;
        font-size: 20px;
        font-weight: bold;
        color: rgb(241, 192, 28);
      }
    }
  }
}
</style>